package com.longkier.gx_library_springboot.Controller;

import com.longkier.gx_library_springboot.Service.BookTypeService;
import com.longkier.gx_library_springboot.entity.BookType;
import com.longkier.gx_library_springboot.utils.RequestUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
@RequestMapping("/Type")
public class BookTypeController {

    private final BookTypeService bookTypeService;

    // 获取所有借阅类别
    @GetMapping("/all")
    public Map<String, Object> getAllBookTypes() {
        try {
            List<BookType> bookTypes = bookTypeService.getAllBookTypes();
            return RequestUtils.buildResponse(bookTypes, 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("获取借阅类别时发生异常", 500);
        }
    }

    // 根据ID获取借阅类别
    @GetMapping("/{id}")
    public Map<String, Object> getBookTypeById(@PathVariable Long id) {
        try {
            return bookTypeService.getBookTypeById(id)
                    .map(bookType -> RequestUtils.buildResponse(bookType, 200))
                    .orElse(RequestUtils.buildResponse("借阅类别不存在", 404));
        } catch (Exception e) {
            return RequestUtils.buildResponse("获取借阅类别时发生异常", 500);
        }
    }

    // 保存新借阅类别
    @PostMapping("/save")
    public Map<String, Object> saveBookType(@RequestBody BookType bookType) {
        try {
            BookType savedBookType = bookTypeService.saveOrUpdateBookType(bookType);
            return RequestUtils.buildResponse(savedBookType, 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("保存借阅类别时发生异常", 500);
        }
    }

    // 更新借阅类别
    @PutMapping("/update/{id}")
    public Map<String, Object> updateBookType(@PathVariable Long id, @RequestBody BookType bookType) {
        try {
            bookType.setTypeId(id);
            BookType updatedBookType = bookTypeService.saveOrUpdateBookType(bookType);
            return RequestUtils.buildResponse(updatedBookType, 200);
        } catch (Exception e) {
            return RequestUtils.buildResponse("更新借阅类别时发生异常", 500);
        }
    }

    // 删除借阅类别
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteBookType(@PathVariable Long id) {
        bookTypeService.deleteBookType(id);
        return RequestUtils.buildResponse("借阅类别删除成功", 200);
    }
}
